<template>
  <!-- 设备故障脱扣记录  -->
  <div class="p-3 d-flex flex-column my-container">
    <div class="">
      <el-form :model="searchReportForms" :inline="true" class="d-flex justify-content-end">
        <el-form-item>
          <el-input v-model="searchReportForms.reportName"  clearable @clear="searchClick" placeholder="请输入报表名称" prefix-icon="el-icon-search"/>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchReportForms.time"
            type="daterange"
            @change="searchClick"
            :picker-options="setDisabled"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="col d-flex flex-column shadow p-3 rounded-lg">
      <div class="mb-3">
        <el-button type="primary" icon="el-icon-plus" v-permission="'BB_SBGZTK_ADD'" @click="handlerAccount">新建报表</el-button>
        <el-button type="success" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </div>
      <div class="col d-flex over-auto">
        <el-table v-loading="loading" border :data="tableData" height="100%">
          <el-table-column type="index" label="序号" width="50" align="center"/>
          <el-table-column prop="reportCode" label="报表编码" align="center"/>
          <el-table-column prop="reportName" label="报表名称" align="center"/>
          <el-table-column prop="accountType" label="报表状态" align="center" width="130">
            <template #default="{ row }">
              <el-tag
                :type="reportStatusList[row.reportStatus].color">{{reportStatusList[row.reportStatus].label}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="起始时间" align="center" width="200">
            <template slot-scope="scope">
              {{ scope.row.startTime }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" width="200">
            <template slot-scope="scope">
              {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column prop="reportStopDes" label="异常终止描述" align="center"/>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="mini" :disabled="row.reportStatus != '1'" @click="handlerCheck(row)">查看
              </el-button>
              <el-button type="danger" size="mini" :disabled="row.reportStatus != '1'" @click="handlerDelete(row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination class="pagination" :total="count" :page.sync="tablePage.pageIndex" :limit.sync="tablePage.pageSize"
                  @pagination="pagination"/>
    </div>


    <!-- 弹框 -->
    <yc-dialog ref="ycDialog" dialogTitle="新建" :showCenter="false">
      <template #content>
        <el-form ref="loginFormRef" :rules="rules" :model="newAccountModel" v-loading="tableLoading" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="报表名称" prop="reportName">
                <el-input v-model="newAccountModel.reportName"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="起始时间" prop="time">
                <el-date-picker
                  v-model="newAccountModel.time"
                  type="datetimerange"
                  style="width: 100%;"
                  :picker-options="setDisabled"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          <el-row>-->
          <!--            <el-col :span="12">-->
          <!--              <el-form-item label="操作人" prop="userCode">-->
          <!--                <el-select v-model="newAccountModel.operationCode" placeholder="请选择" style="width: 100%;">-->
          <!--                  <el-option-->
          <!--                    v-for="item in userList"-->
          <!--                    :key="item.userCode"-->
          <!--                    :label="item.userName"-->
          <!--                    :value="item.userCode">-->
          <!--                  </el-option>-->
          <!--                </el-select>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--            <el-col :span="12">-->
          <!--              <el-form-item label="操作类型" prop="accountPhone">-->
          <!--                <el-checkbox-group v-model="newAccountModel.operateType">-->
          <!--                  <el-checkbox v-for="(item, index) in operationTypeList" :key="index" :label="item.value"-->
          <!--                               :value="item.value">{{item.name}}-->
          <!--                  </el-checkbox>-->
          <!--                </el-checkbox-group>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--          </el-row>-->
          <el-row>
            <el-col :span="6">
              <div class="mt-2 font-16">设备筛选</div>
            </el-col>
            <el-col :span="18">
              <el-form :model="serchDeviceForm" class="d-flex justify-content-end" size="small" :inline="true">
                <el-form-item label="设备名称:">
                  <el-input v-model="serchDeviceForm.deviceName" clearable @clear="deviceSearch" placeholder="请输入设备名称"/>
                </el-form-item>
                <el-form-item label="设备编码:">
                  <el-input v-model="serchDeviceForm.deviceCode" clearable @clear="deviceSearch" placeholder="请输入设备编码"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="deviceSearch">查询</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>

          <el-table max-height="200px" border size="small" :data="equipmentList">
            <el-table-column type="index" label="序号" width="80" align="center"/>
            <el-table-column prop="deviceName" label="设备名称" align="center"/>
            <el-table-column prop="deviceCode" label="设备编码" align="center"/>
            <el-table-column prop="deviceDes" label="设备描述" align="center"/>
            <el-table-column prop="createTime" label="" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  :type="equipmentSelectList.findIndex(item => item.deviceCode == scope.row.deviceCode) == -1 ? 'primary' : 'danger'"
                  size="mini"
                  @click="onEquipmentSelect(scope.row)">{{ equipmentSelectList.findIndex(item =>
                  item.deviceCode == scope.row.deviceCode) == -1 ? "选择" : "删除" }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination class="pagination" :total="equipmentPage.total" :page.sync="equipmentPage.pageIndex"
                      :limit.sync="equipmentPage.pageSize" @pagination="equipmentPagination"/>
          <div class="mb-4 font-16">已选择设备</div>
          <el-table max-height="200px" border size="small" :data="equipmentSelectList">
            <el-table-column type="index" label="序号" width="80" align="center"/>
            <el-table-column prop="deviceName" label="设备名称" align="center"/>
            <el-table-column prop="deviceCode" label="设备编码" align="center"/>
            <el-table-column prop="deviceDes" label="设备描述" align="center"/>
            <el-table-column prop="createTime" label="" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="onEquipmentSelect(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" :disabled="btnLoading" @click="dialogSave">保存</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message v-if="isGlobalMessageShow" @receive="receive" :message="message"/>
  </div>
</template>

<script>
  import {
    insertReportTypeGZTK,
    queryImplementAllAccount,
    queryReportRuleMainPage,
    deleteReportMain
  } from "@/api/reportStatistics/index"
  import { queryPageDevice } from "@/api/userControl/role"
  import ycDialog from "@/components/pageDialog"


  export default {
    data() {
      return {
        loading: false,
        isGlobalMessageShow: false,
        message: "",
        tableData: [],
        count: 0,
        tablePage: {
          pageIndex: 1,
          pageSize: 20
        },

        reportStatusList: [
          { status: "0", color: "", label: "查询中" },
          { status: "1", color: "success", label: "查询完成" },
          { status: "2", color: "danger", label: "异常中止" }
        ],
        searchReportForms: {
          reportName: "",
          time: ""
        },
        userList: [],
        operationTypeList: [
          { value: "open", name: "合闸" },
          { value: "close", name: "分闸" },
          { value: "change", name: "参数修改" }
        ],
        newAccountModel: {
          reportName: "",
          // operationCode: null,
          time: "",
          // operateType: [],
          reportType: "4"
        },
        rules: {
          reportName: [{
            required: true,
            message: "请输入报表名称",
            trigger: "blur"
          }],
          time: [{
            type: "array",
            required: true,
            message: "请选择起始时间",
            fields: {
              0: {
                type: "string", //tpye类型试情况而定,所以如果返回的是date就改成date
                required: true,
                trigger: "change",
                message: "请选择开始时间"
              },
              1: {
                type: "string",
                required: true,
                trigger: "change",
                message: "请选择结束时间"
              }
            }
          }]
          // accountPhone: [{
          //   required: true,
          //   trigger: "blur",
          //   message: "请输入手机号码"
          // }]
        },

        serchDeviceForm: {
          deviceName: "",
          deviceCode: ""
        },
        equipmentList: [], //设备权限列表
        equipmentSelectList: [], //设备权限列表
        equipmentPage: {
          total: 0,
          pageIndex: 1,
          pageSize: 10
        },
        tableLoading: false,
        btnLoading: false,
        setDisabled: {
          disabledDate(time) {
            return time.getTime() > Date.now(); // 可选历史天、可选当前天、不可选未来天
            // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
            // return time.getTime() < Date.now() - 8.64e7;  // 不可选历史天、可选当前天、可选未来天
            // return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
          },
        },
      }
    },
    components: {
      ycDialog
    },
    created() {
      this.queryReportRuleMainPage()
    },
    methods: {
      /**
       * 获取表格方法
       */
      queryReportRuleMainPage() {
        this.loading = true
        const { reportName, time } = this.searchReportForms
        queryReportRuleMainPage({
          ...this.tablePage,
          reportType: "4",
          // reportName,
          // mapString1: time && time[0],
          // mapString2: time && time[1]
        }).then(res => {
          if (res.status == 200) {
            this.tableData = res.object.data
            this.count = res.object.count
            this.loading = false
          }
        })
      },

      pagination(pageItem) {
        this.queryReportRuleMainPage(pageItem.page, pageItem.limit)
      },
      /**
       * 查看按钮
       */
      async handlerCheck(row) {
        this.$router.push({
          path: "/reportStatistics/deviceFaultRecordDetail",
          query: { reportCode: row.reportCode }
        })
      },

      // 搜索按钮
      async searchClick() {
        this.queryReportRuleMainPage()
      },
      /**
       * 刷新
       */
      refresh() {
        this.searchReportForms = {
          reportName: "",
          time: ""
        }
        this.queryReportRuleMainPage()
      },
      /**
       * 删除按钮
       */
      async handlerDelete({ id, reportCode }) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {
            status
          } = await deleteReportMain({
            reportCode
          })
          if (status == "200") {
            this.queryReportRuleMainPage()
            this.isGlobalMessageShow = true
            this.message = "success"
          }
        })
      },


      /**
       * 打开新建报表弹窗
       * */
      async handlerAccount() {
        // this.queryImplementAllAccount()
        this.queryConfigurableDevice()
        if (this.$refs.loginFormRef) {
          this.$refs.loginFormRef.clearValidate()
          this.$refs.loginFormRef.resetFields()
        }
        this.equipmentSelectList = []
        this.tableLoading = false
        this.btnLoading = false
        this.$refs.ycDialog.dialogVisible = true
      },
      // 查询操作人
      queryImplementAllAccount() {
        queryImplementAllAccount().then(res => {
          if (res.status == 200) {
            this.userList = res.object
          }
        })
      },
      // 查询设备列表
      queryConfigurableDevice() {
        const { deviceName, deviceCode } = this.serchDeviceForm
        queryPageDevice({
          pageIndex: this.equipmentPage.pageIndex,
          pageSize: this.equipmentPage.pageSize,
          deviceType: 0,
          deviceName,
          deviceCode
        }).then(res => {
          this.equipmentList = res.object.data
          this.equipmentPage.total = res.object.count
        })
      },
      // 选择设备
      onEquipmentSelect(row) {
        let index = this.equipmentSelectList.findIndex(item => item.id == row.id)
        if (index == -1) {
          this.equipmentSelectList.push(row)
        } else {
          this.equipmentSelectList.splice(index, 1)
        }
      },
      equipmentPagination(pageItem) {
        this.queryConfigurableDevice(pageItem.page, pageItem.limit)
      },
      deviceSearch() {
        this.queryConfigurableDevice()
      },
      dialogSave() {
        this.$refs.loginFormRef.validate(async (v) => {
          if (v) {
            this.tableLoading = true
            this.btnLoading = true
            const {
              reportName,
              // operationCode,
              reportType
            } = this.newAccountModel

            const startTime = this.newAccountModel.time[0]
            const endTime = this.newAccountModel.time[1]
            let deviceList = this.equipmentSelectList.map(item => {
              return {
                deviceName: item.deviceName,
                deviceCode: item.deviceCode
              }
            })
            insertReportTypeGZTK({
              reportName,
              // operationCode,
              reportType,
              startTime,
              endTime,
              // operateType,
              mapString1: JSON.stringify(deviceList)
            }).then(res => {
              if (res.status == 200) {
                this.queryReportRuleMainPage()
                this.$message.success(res.message)
                this.$refs.ycDialog.dialogVisible = false
              }
              this.tableLoading = false
              this.btnLoading = false
            })
          }
        })
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    height: 600px;

    .drawer-title {
      font-weight: 400;
      font-size: 24px;
      color: #000000;
      text-align: center;
      padding: 36px 0;
    }

    .form {
      padding: 0 10px;
    }
  }

  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
